package com.benyanyi.okhttp.call;

import android.content.Context;

import com.benyanyi.okhttp.config.CallType;
import com.benyanyi.okhttp.listener.OnOkHttpListener;

import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author YanYi
 * @date 2019-08-02 22:23
 * @email ben@yanyi.red
 * @overview 数据请求
 */
public class HttpCall implements RequestConfig {

    private CallBuilder builder;

    private HttpCall(Builder builder) {
        Call call = builder.httpClient.newCall(builder.request);
        this.builder = new CallBuilder()
                .setCache(builder.isCache)
                .setCacheName(builder.mCacheUrl)
                .setContext(builder.context)
                .setCall(call);
    }

    @Override
    public <T> void async(Class<T> tClass, OnOkHttpListener<T> onOkHttpListener) {
        this.builder.setCallType(CallType.ASYNC).builder(tClass).send(onOkHttpListener);
    }

    @Override
    public <T> void sync(Class<T> tClass, OnOkHttpListener<T> onOkHttpListener) {
        this.builder.setCallType(CallType.SYNC).builder(tClass).send(onOkHttpListener);
    }

    @Override
    public <T> void asyncList(Class<T> tClass, OnOkHttpListener<List<T>> onOkHttpListener) {
        this.builder.setCallType(CallType.ASYNC).listBuilder(tClass).send(onOkHttpListener);
    }

    @Override
    public <T> void syncList(Class<T> tClass, OnOkHttpListener<List<T>> onOkHttpListener) {
        this.builder.setCallType(CallType.SYNC).listBuilder(tClass).send(onOkHttpListener);
    }

    @Override
    public void async(OnOkHttpListener<Object> onOkHttpListener) {
        this.builder.setCallType(CallType.ASYNC).builder().send(onOkHttpListener);
    }

    @Override
    public void sync(OnOkHttpListener<Object> onOkHttpListener) {
        this.builder.setCallType(CallType.SYNC).builder().send(onOkHttpListener);
    }

    public static class Builder {

        private Context context;
        private String mCacheUrl;
        private Request request;
        private OkHttpClient httpClient;
        private boolean isCache;//是否需要缓存

        public Builder setContext(Context context) {
            this.context = context;
            return this;
        }

        public Builder setCacheUrl(String mCacheUrl) {
            this.mCacheUrl = mCacheUrl;
            return this;
        }

        public Builder setRequest(Request request) {
            this.request = request;
            return this;
        }

        public Builder setHttpClient(OkHttpClient httpClient) {
            this.httpClient = httpClient;
            return this;
        }

        public Builder setCache(boolean cache) {
            isCache = cache;
            return this;
        }

        public RequestConfig builder() {
            return new HttpCall(this);
        }
    }

}
